package gov.mogaha.ntis.cmm.mob;

import gov.mogaha.ntis.cmm.mob.baseactivity.BaseActivity;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServlet;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServlet.DataSet;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServletHandler;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServletHandler.HttpResult;
import gov.mogaha.ntis.cmm.mob.util.Logger;
import gov.mogaha.ntis.cmm.mob.util.Toaster;
import gov.mogaha.ntis.cmm.mob.view.EditTextView;
import gov.mogaha.ntis.cmm.mob.view.TitleView;
import gov.mopas.mobile.gis.R;
import gov.mopas.mobile.gis.baseType.Geometry;
import gov.mopas.mobile.gis.baseType.Item;
import gov.mopas.mobile.gis.baseType.LonLat;
import gov.mopas.mobile.gis.baseType.Pixel;
import gov.mopas.mobile.gis.baseType.PnuVO;
import gov.mopas.mobile.gis.handler.MapHandler;
import gov.mopas.mobile.gis.handler.PnuHandler;
import gov.mopas.mobile.gis.layer.ItemLayer;
import gov.mopas.mobile.gis.util.ProjectionUtil;
import gov.mopas.mobile.gis.util.constants.InitSettings;
import gov.mopas.mobile.gis.view.MapController;
import gov.mopas.mobile.gis.view.MapView;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;

import wire.proto.Binding;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.droid.geom.Point;

public class CmmMobJibunAddrInsert extends BaseActivity implements OnClickListener {
	/**<B>String addrOVERALL</B><BR>
	 * 주소검색 및 건물번호 등 사용자 입력으로 인해 현재 단계까지 생성된 주소 문자열*/
	String addrOVERALL = "";
		
	TitleView titleView;	// 타이틀뷰
	
	// Map 관련 변수 Start
	MapView mView;			// MapView
	MapController mCtrl;	// MapController
	final static String EPSG_GOOGLE = "EPSG:900913";
	LonLat mCurLonLat;
	ItemLayer thumbnailPopupLayer;
	ItemLayer curMyPositionLayer;
	ItemLayer poiSrchLayer;
	ItemLayer poiSrchListLayer;	
	ItemLayer calcDitancePointLayer;
	ItemLayer calcDitanceLineLayer;
	
	ItemLayer itemLayer;
	
	Spinner mRadiusSpinner;
	// Map 관련 변수 End
	
	//시, 읍면동 검색
	/**<B>String addrSI</B><BR>
	 * 공통앱에서 넘어온 전체 시/군/구 정보값 문자열*/
	String addrSI;
	/**<B>String exTempData</B><BR>
	 * 검색 리스트를 받아온 이력을 저장하는 변수. 
	 * 검색 키워드가 최근 검색 이력 키워드와 같으면 네트워크를 사용하지 않고 저장된 정보를 재사용한다.*/
	String exTempData = "";
	
	TextView cnt;
	EditTextView editKeyword;
	Button btnKeyword;
	
	Button btnGisStart;
	String pnu;
	
	ListView addrList;
	ArrayList<Hashtable<String, String>> rstData;
	Hashtable<String, String> selectedData;
	
	//산구분
	/**<B>boolean isSan</B><BR>
	 * 번지가 산 번지인지 일반 번지인지를 저장하는 변수.*/
	boolean isSan = false;
	
	RadioGroup btnSanGroup;
	RadioButton btnSanNormal;
	RadioButton btnSanSan;
	
	
	//번지
	EditText editBunji;
	
	//호
	EditText editHo;
	
	
	//확인,  취소버튼
	Button btnFindStart;
	Button btnCancel;
	
	//주소목록 레이아웃
	LinearLayout jusoLayout;
	
	
	//이전 데이터가 있는지 여부
	Address address;
	boolean exdataTransed = false;
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Map 관련 Init Method
		setMapArea();
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.cmm_mob_jibun_addr_insert);
		
		
		
		//타이틀
		TitleView title = (TitleView)findViewById(R.id.title_Cn);
		title.setTitle("주소 검색");
		title.setBackgroundImage(R.drawable.titlebarsub);
		
		mView = (MapView)findViewById(R.id.mapview);	// MapView
		
		//위젯 초기화
		init();
		
		
		//기존에 입력된 주소가 있으면 가져옴
		try {
			Intent transedIntent = getIntent();
			address = (Address) transedIntent.getSerializableExtra("data");
			editKeyword.setText(Address.parseAddress(address));
			exdataTransed = true;
		} catch (Exception e) {
			e.getMessage();
		}
	}



	private void init() {
		//검색어 입력 및 결과값 입력
		editKeyword = (EditTextView)findViewById(R.id.edit_JibunAddr_Keyword);

		cnt = (TextView)findViewById(R.id.text_AddrListView_ItemCount);
		
		editKeyword.setHint("예) 도렴동, 신사동");
		
		// 위치찾기 Button Start
		//btnGisStart = (Button)findViewById(R.id.btn_Gis_FindStart);
		//btnGisStart.setOnClickListener(this);
		// 위치찾기 Button End
		
		btnKeyword = (Button)findViewById(R.id.btn_JibunAddr_Keyword);
		btnKeyword.setOnClickListener(this);
		btnSanGroup = (RadioGroup)findViewById(R.id.btn_JibunAddr_SanGroup);
		btnSanNormal = (RadioButton)findViewById(R.id.btn_JibunAddr_San_Normal);
		btnSanSan = (RadioButton)findViewById(R.id.btn_JibunAddr_San_San);
		
		jusoLayout = (LinearLayout)findViewById(R.id.juso_srch_list_layout);
		addrList = (ListView)findViewById(R.id.juso_list);
		addrList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				editKeyword.setText(rstData.get(position).get("sido_nm")+" "+rstData.get(position).get("cgg_nm")+" "+rstData.get(position).get("umd_nm"));
				jusoLayout.setVisibility(View.GONE);
				selectedData = rstData.get(position);
				exdataTransed = false;
			}
		});
		
		//번지
		editBunji = (EditText)findViewById(R.id.edit_Jibun_Bunji);
		
		//호
		editHo = (EditText)findViewById(R.id.edit_Jibun_Ho);
		Button btn_Jibun_FindStart = (Button)findViewById(R.id.btn_Jibun_FindStart);
		btn_Jibun_FindStart.setOnClickListener(this);
		Button btn_Jibun_Cancel = (Button)findViewById(R.id.btn_Jibun_Cancel);
		btn_Jibun_Cancel.setOnClickListener(this);
		
		/*
		// MapHandler 관련 Start
		mView.setMapHandler(new MapHandler() {			
			
			@Override
			public void onMapLoaded() {				
				setDefaultLonLat();
				afterMapLoad();
				initLayer();
				mCtrl.setCenter(mCurLonLat);
				
				
			}
			@Override
			public void onZoomChanged() {
				//this.onZoomChanged();
			}
			@Override
			public void onMapDragStart() {
				// TODO Auto-generated method stub
			}
			@Override
			public void onMapDragEnd() {
				// TODO Auto-generated method stub
			}
		});
		// MapHandler 관련 End
		 */
	}



	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_JibunAddr_Keyword:
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
	        imm.hideSoftInputFromWindow(editKeyword.getWindowToken(), 0);   
	   
			if (editKeyword.getText().toString().length()>1) {
				Binding param = new Binding();
				param.put("umd_nm", editKeyword.getText().toString());
				
				CmmMobServletHandler handle = new CmmMobServletHandler(CmmMobJibunAddrInsert.this);
				new CmmMobServlet(CmmMobJibunAddrInsert.this, 
						"mobile/RTP_MOB_CMM", "MOBCMM", "selectListJibunAddr", 
						handle.getHandler(new HttpResult() {
							@Override
							public void httpCallback(DataSet data) {
								rstData = data.getHashData();
								
								addrList.setAdapter(new addrListAdapter(rstData));
								if (rstData.size()>0) {
									addrList.getLayoutParams().height = rstData.size()>5 ? 
											getResources().getDimensionPixelSize(R.dimen.addr_jibun_list_item_height)*(5) : 
											getResources().getDimensionPixelSize(R.dimen.addr_jibun_list_item_height)*(rstData.size());
									cnt.setText("(검색됨: "+rstData.size()+")");
									
									jusoLayout.setVisibility(View.VISIBLE);
								}else {
									Toaster.showMsg(CmmMobJibunAddrInsert.this, "조회된 결과가 없습니다.");
								}
							}
						}), 
						param).start();
				
				exdataTransed = false;
			}else {
				Toaster.showMsg(CmmMobJibunAddrInsert.this, "두자리 이상 입력되어야 합니다.");
			}
			break;
			
			
		case R.id.btn_Jibun_FindStart:
			if (!editKeyword.getText().toString().equals("")) {
				Address addrData = getAddress();
				Intent dataIntent = new Intent();
				String san = btnSanNormal.isChecked()  ? "1" : "2";
				String bunji = editBunji.getText().toString();
				String ho = editHo.getText().toString();
				StringBuilder builder = new StringBuilder(editKeyword.getText().toString() + " ");
				if ("2".equals(san)) builder.append("산");
				builder.append(bunji);
				if (!"".equals(ho)) builder.append("-"+ho);
				addrData.setaddrOverall(builder.toString());
				//기존에 Address개체가 들어왔을 경우 기존 데이터를 사용
				if (exdataTransed) {
					addrData.setaddrBunji(bunji);
					addrData.setaddrHo(ho);
					addrData.setaddrSan(san);
					addrData.setaddrIsSan(btnSanNormal.isChecked()  ? "일반" : "산");
				//들어오지 않았을 경우 폼의 정보를 사용
				} else {
					addrData.setRi_nm(selectedData.get("riNm"));
					addrData.setRegn_code(selectedData.get("regn_code"));
					addrData.setAdmdng_code(selectedData.get("admdng_code"));
					addrData.setSido_nm(selectedData.get("sido_nm"));
					addrData.setCgg_nm(selectedData.get("cgg_nm"));
					addrData.setAdmdng_nm(selectedData.get("admdng_nm"));
					addrData.setUmd_nm(selectedData.get("umd_nm"));
					addrData.setaddrBunji(bunji);
					addrData.setaddrHo(ho);
					addrData.setaddrSan(san);
					addrData.setaddrIsSan(btnSanNormal.isChecked() ? "일반" : "산");
				}
				dataIntent.putExtra("data", addrData);
				dataIntent.putExtra("ADDRESS_STRING", addrData.getaddrOverall());
				
				setResult(RESULT_OK, dataIntent);
				finish();
				
			}else {
				Toaster.showMsg(CmmMobJibunAddrInsert.this, "주소검색이 이루어지지 않았습니다. 다시 확인해주세요.");
			}
			break;

			
		case R.id.btn_Jibun_Cancel:
			setResult(RESULT_CANCELED);
			finish();
			break;
		/*
		// PNU를 이용한 Search
		case R.id.btn_Gis_FindStart:
			//Address address = getAddress();
			pnu = "3011011900100010001";
			
			if(!"".equals(editKeyword.getText().toString()) && (address != null) && (address.getRegn_code().length() == 10)){
				pnu = StringUtil.makePnu(address.getRegn_code(), address.getaddrSan(), address.getaddrBunji(), address.getaddrHo());
				Toaster.showMsg(CmmMobJibunAddrInsert.this, "PNU:" +pnu);
				
			}else{
				Toaster.showMsg(CmmMobJibunAddrInsert.this, "주소검색이 이루어지지 않았습니다. 다시 확인해주세요.");
			}
			
			findLocationByPnu();
			Message msg = Message.obtain();
			msg.obj = pnu;
			mPnuHander.sendMessage(msg);
			break;
		*/
		default:
			break;
		}
	}
	
	/**
	 * Address VO를 만드는 메소드
	 */
	private Address getAddress(){		
		Address addrData = null;		
		if (!editKeyword.getText().toString().equals("")) {
			if (address == null) addrData = new Address();
			else addrData = address;
			
			//addrOverall 정보(전체 주소) 저장
			String san = btnSanNormal.isChecked()  ? "1" : "2";
			String bunji = editBunji.getText().toString();
			String ho = editHo.getText().toString();
			StringBuilder builder = new StringBuilder(editKeyword.getText().toString() + " ");
			if ("2".equals(san)) builder.append("산");
			builder.append(bunji);
			if (!"".equals(ho)) builder.append("-"+ho);
			addrData.setaddrOverall(builder.toString());
			
			//기존에 Address개체가 들어왔을 경우 기존 데이터를 사용
			if (exdataTransed) {
				addrData.setaddrBunji(bunji);
				addrData.setaddrHo(ho);
				addrData.setaddrSan(san);
				addrData.setaddrIsSan(btnSanNormal.isChecked()  ? "일반" : "산");
			//들어오지 않았을 경우 폼의 정보를 사용
			} else {
				addrData.setRi_nm(selectedData.get("riNm"));
				addrData.setRegn_code(selectedData.get("regn_code"));
				addrData.setAdmdng_code(selectedData.get("admdng_code"));
				addrData.setSido_nm(selectedData.get("sido_nm"));
				addrData.setCgg_nm(selectedData.get("cgg_nm"));
				addrData.setAdmdng_nm(selectedData.get("admdng_nm"));
				addrData.setUmd_nm(selectedData.get("umd_nm"));
				addrData.setaddrBunji(bunji);
				addrData.setaddrHo(ho);
				addrData.setaddrSan(san);
				addrData.setaddrIsSan(btnSanNormal.isChecked()  ? "일반" : "산");
			}
		}
		return addrData;
	}
	
	
	// Map 관련 Method Start
	/**
	 * 맵의 지역을 설정한다.
	 */
	private void setMapArea(){
		InitSettings.setMapArea(InitSettings.DAEJEON);
	}
	
	private void afterMapLoad(){
		mCtrl = mView.getMapController();
		itemLayer = new ItemLayer(this);
		mView.addLayer(itemLayer); 
	}
	PnuHandler mPnuHander = new PnuHandler() {
		
		@Override
		public void onSuccess(PnuVO pnuVo) {
			// TODO Auto-generated method stub
			Map<String,Geometry> map = pnuVo.getGeomMap();
	    	Geometry geom = (Geometry)map.get("pnu");
	    	Item item = new Item(geom,null);
	    	itemLayer.items.add(item);
	    	mView.refreshAll();
	    	mCtrl.setBounds(item.getBounds());
	    	Logger.d( "findLocationByPnu:" + geom.toString());
		}
		
		@Override
		public void onFail() {
			// TODO Auto-generated method stub
			
		}
	};
	
	private void findLocationByPnu(){
		mCtrl.getPnuAsync(new Pixel(200, 200),mPnuHander, PnuVO.PNU | PnuVO.EMD); 
	}
	
	/**
	 * GPS및 Network로 위치 수진전 기본적인 위치를 강제로 고정한다.
	 */
	private void setDefaultLonLat(){
		
		//대전
		mCurLonLat = getTransLonLat(EPSG_GOOGLE, new Point(127.38501, 36.35120));

		//부산
		//mCurLonLat = getTransLonLat(EPSG_GOOGLE, new Point(128.9994128311111, 35.104350919999995));
	}
	
	/**
	 * 좌표체계를 변환한다.
	 * @param src
	 * @param point
	 * @return
	 */
	protected LonLat getTransLonLat(String src, Point point ){
		ProjectionUtil proj = ProjectionUtil.getInstance(src);
		return new LonLat(proj.degree2TileXY(point));
	}
	
	/**
	 * Layer를 초기화한다.
	 */
	private void initLayer(){
		
		thumbnailPopupLayer = new ItemLayer(this);
		curMyPositionLayer = new ItemLayer(this);
		calcDitancePointLayer = new ItemLayer(this);
		calcDitanceLineLayer = new ItemLayer(this);
		poiSrchLayer = new ItemLayer(this);
		poiSrchListLayer = new ItemLayer(this);
		
		mView.addLayer(poiSrchLayer); 
		mView.addLayer(poiSrchListLayer); 
		mView.addLayer(calcDitancePointLayer); 
		mView.addLayer(calcDitanceLineLayer); 
		mView.addLayer(curMyPositionLayer); 
		mView.addLayer(thumbnailPopupLayer); 
		

		
		Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.icon_me);
		Item item = new Item(mCurLonLat, bitmap, mCurPositionCallbackHandler);
		
		curMyPositionLayer.getItemList().add(item);	
	}
	
	private final Handler mCurPositionCallbackHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			if(mCurLonLat!=null)
				mCtrl.setCenter(mCurLonLat);
		}
	};
	
	// Map 관련 Method End
	
	
	
	class addrListAdapter extends BaseAdapter {
		ArrayList<Hashtable<String, String>> data;
		
		public addrListAdapter(ArrayList<Hashtable<String, String>> lData) {
			data = lData;
		}
		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Hashtable<String, String> tmp = data.get(position);
			LayoutInflater factory = LayoutInflater.from(CmmMobJibunAddrInsert.this);
			convertView = factory.inflate(R.layout.address_list_resource, null);
			TextView t1 = (TextView)convertView.findViewById(R.id.addr_list_item1);
			TextView t2 = (TextView)convertView.findViewById(R.id.addr_list_item2);
			TextView t3 = (TextView)convertView.findViewById(R.id.addr_list_item3);
			TextView t4 = (TextView)convertView.findViewById(R.id.addr_list_item4);
			
			t1.setText(tmp.get("sido_nm"));
			t2.setText(tmp.get("cgg_nm"));
			t3.setText(tmp.get("umd_nm"));
			t4.setText(tmp.get("admdng_nm"));
			return convertView;
		}
	}
}









